package com.sh.rbac.domain.converter;

import com.sh.rbac.domain.entity.OperationLog;
import com.sh.rbac.domain.enums.OperationStatusEnum;
import com.sh.rbac.domain.enums.OperationTypeEnum;
import com.sh.rbac.domain.vo.operationLog.OperationLogVO;
import com.sh.rbac.utils.IpAddressUtils;
import org.mapstruct.*;
import org.mapstruct.factory.Mappers;

import java.util.List;

/**
 * 操作日志对象转换器
 *
 * @author wb
 * @since 2024-07-07
 */

@Mapper
public interface OperationLogConverter {

    OperationLogConverter INSTANCE = Mappers.getMapper(OperationLogConverter.class);


    /**
     * 将 OperationLog 转换为 OperationLogVO
     *
     * @param operationLog 操作日志实体类
     * @return 操作日志视图传输对象
     */
    @Mapping(target = "operationAddr", ignore = true)
    @Mapping(target = "operationType", source = "operationType", qualifiedByName = "getOperationTypeDescription")
    @Mapping(target = "operationStatus", source = "operationStatus", qualifiedByName = "getOperationStatusDescription")
    @Mapping(target = "requestTime", source = "requestTime", qualifiedByName = "getRequestTimeFormat")
    OperationLogVO operationLogToOperationLogVO(OperationLog operationLog);


    /**
     * 将 OperationLogList 转换为 OperationLogVOList
     *
     * @param operationLogList 操作日志实体类集合
     * @return 操作日志视图传输对象集合
     */
    List<OperationLogVO> convertToOperationLogVOList(List<OperationLog> operationLogList);


    /**
     * 设置操作地址
     *
     * @param operationLog   操作日志实体类
     * @param operationLogVO 操作日志视图传输对象
     */
    @AfterMapping
    default void setLoginAddr(OperationLog operationLog, @MappingTarget OperationLogVO operationLogVO) {
        operationLogVO.setOperationAddr(IpAddressUtils.getIpPossessionByFile(operationLog.getOperationIp()));
    }


    @Named("getOperationTypeDescription")
    default String getOperationTypeDescription(Integer operationType) {
        return OperationTypeEnum.getDescByCode(operationType);
    }

    @Named("getOperationStatusDescription")
    default String getOperationStatusDescription(Integer operationStatus){
        return OperationStatusEnum.getDescByCode(operationStatus);
    }

    @Named("getRequestTimeFormat")
    default String getRequestTimeFormat(Integer requestTime){
        if(requestTime == null){
            return "0 ms";
        }
        return requestTime + " ms";
    }
}
